<?php
class SleekCMS_RegisterModule extends Module {
	public function run () {
		$form = new Form('register', '', 'post', t('Register'), array_merge(User()->asArray(), $_POST));

		$form->addField(array(
			'name'			=> 'username', 
			'title'			=> t('Username'), 
			'placeholder'	=> t('Your preferred username'), 
			'required'		=> true
		));
		$form->addField(array(
			'name'			=> 'email', 
			'type'			=> 'email', 
			'title'			=> t('E-mail'), 
			'placeholder'	=> t('Your e-mail address'), 
			'required'		=> true
		));

		if ($data = $form->isSubmitted()) {
			if ($form->validate()) {
				if (UsersModel::getByEmail($data['email'])) {
					$form->setError(t("E-mail address taken.")); # TODO: setError($msg, $field = 'email')
				}
				elseif (UsersModel::getByUsername($data['username'])) {
					$form->setError(t("Username taken.")); # TODO: setError($msg, $field = 'username')
				}
				else {
					$user = new UserModel(array(
						'username'	=> $data['username'], 
						'email'		=> $data['email']
					));

					$newPassword = UsersModel::getRandomPassword();

					$user->setPassword($newPassword);
					$user->save();

					mail(
						$user->getEmail(), 
						t('Thank you for registering'), 
						t('You have successfully registered with %0. Your randomly generated password is: %1', array(conf('general.site_title'), $newPassword))
					);

					# TODO: remove later
					$form->setMessage(t('You have successfully registered with %0. Your randomly generated password is: %1', array(conf('general.site_title'), $newPassword)));
				}
			}
			else {
				$form->setError(t('Make sure you fill out all the fields properly.'));
			}
		}

		$this->setData('form', $form->asHTML());
	}
}
